//
//  HotCollectionViewController.m
//  ChooseGift
//
//  Created by lanou on 15/12/21.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "HotCollectionViewController.h"
#import "ChooseGift.h"
#import "MJRefresh.h"
#import "ChooseGiftCollectionViewCell.h"
#import "WebViewController.h"
#import "MJRefresh.h"

@interface HotCollectionViewController ()

@property (nonatomic,strong) NSMutableArray *modelarray;

@property (nonatomic,strong) NSMutableArray *idArray;

@property(nonatomic, strong) UIButton *openDrawerButton;


@end
static NSInteger num = 0;
@implementation HotCollectionViewController

static NSString * const reuseIdentifier = @"Cell";
- (NSMutableArray *)modelarray{
    if (!_modelarray) {
        _modelarray = [[NSMutableArray alloc]init];
        
    }
    return _modelarray;
}
- (NSMutableArray *)idArray{
    if (!_idArray) {
        _idArray = [[NSMutableArray alloc]init];
    }
    return _idArray;
}


- (void)setData{
    
    if ([_type isEqualToString:@"搜索框1"])
    {
        //转换成 utf8编码格式
        NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)self.ID, NULL, NULL,  kCFStringEncodingUTF8 ));
        
        NSString *urlString = [[kGift1 stringByAppendingString:encodedString]stringByAppendingString:kGift2];
        NSLog(@"%@",urlString);
        
        [LORequestManger GET:urlString success:^(id response) {
            
            NSDictionary *Dic = (NSDictionary *)response;
            
            NSArray *titleArray = Dic[@"data"][@"items"];
            
            for (NSDictionary *dic in titleArray) {
                ChooseGift *choose = [[ChooseGift alloc]init];
                
                if (self.ID != nil) {
                    [choose setValuesForKeysWithDictionary:dic];
                }else
                {
                    [choose setValuesForKeysWithDictionary:dic[@"data"]];
                }
                
                [self.idArray addObject:choose.ID];
                [self.modelarray addObject:choose];
            }
            [self.collectionView reloadData];
            [self.collectionView headerEndRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
    }else {
    
        NSString *string = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items?gender=1&generation=1&limit=50&offset=%ld",num];
        if (self.ID != nil) {
            NSLog(@"%@_______",self.ID);
            string = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/item_subcategories/%@/items?limit=20&offset=%ld",self.ID,num*2/5];
            }
//        NSURL *url = [NSURL URLWithString:string];
//        NSURLRequest *request = [NSURLRequest requestWithURL:url];
//        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//            NSDictionary *rootvc = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
            [LORequestManger GET:string success:^(id response) {
                NSDictionary *rootvc = (NSDictionary *)response;
                
                NSArray *array = rootvc[@"data"][@"items"];
                for (NSDictionary *dic in array) {
                    ChooseGift *choose = [[ChooseGift alloc]init];
                    
                    if (self.ID != nil) {
                        [choose setValuesForKeysWithDictionary:dic];
                    }else
                    {
                        [choose setValuesForKeysWithDictionary:dic[@"data"]];
                    }
                    
                    [self.idArray addObject:choose.ID];
                    [self.modelarray addObject:choose];
                }
                
                [self.collectionView reloadData];
                [self.collectionView headerEndRefreshing];
                
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"%@",error);
            }];
            
            
//        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setData];
    
    self.title = @"热门";
    
    self.collectionView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    
    __weak HotCollectionViewController *hotCollection = self;
    [self.collectionView addHeaderWithCallback:^{
        _modelarray = [[NSMutableArray alloc]init];
        _idArray = [[NSMutableArray alloc]init];
        [hotCollection setData];
    }];
    if ([_type isEqualToString:@"搜索框1"]) {
        
    }else
    {
        [self.collectionView addFooterWithCallback:^{
            num += 50;
            [hotCollection setData];
            [hotCollection.collectionView footerEndRefreshing];
        }];
    }
    
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
    flowlayout.minimumInteritemSpacing = 10;
    flowlayout.minimumLineSpacing = 10;
    flowlayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    flowlayout.itemSize = CGSizeMake(kWidth / 2 -  20, kHeight * 0.4);
    
    
    self.collectionView.collectionViewLayout = flowlayout;
    //   flowlayout.headerReferenceSize = CGSizeMake(0, 40);
    
    
    
    [self.collectionView registerClass:[ChooseGiftCollectionViewCell class] forCellWithReuseIdentifier:@"HP"];
    [self.view addSubview:self.collectionView];
    
    
    
 
    
    
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.modelarray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ChooseGiftCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HP" forIndexPath:indexPath];
    ChooseGift *choose = self.modelarray[indexPath.row];
    cell.choose = self.modelarray[indexPath.row];
    cell.choose = choose;
    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WebViewController *webvc = [[WebViewController alloc]init];
    webvc.userid = self.idArray[indexPath.row];
    webvc.choosegift = self.modelarray[indexPath.row];
    webvc.type = 1;
    [webvc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:webvc animated:YES];
    
    
}
#pragma mark <UICollectionViewDelegate>

/*
 // Uncomment this method to specify if the specified item should be highlighted during tracking
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
 }
 */

/*
 // Uncomment this method to specify if the specified item should be selected
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
 }
 
 - (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
 }
 
 - (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
 }
 */

@end
